"""
BPM Counter v0.2

author: MagicSteve
"""
import threading
import time
from PySide6.QtWidgets import QApplication, QWidget
from ui_BPMCounter import Ui_Form


class MyWindow(QWidget, Ui_Form):  # 继承QWidget以及生成的Ui_Form
    time = None  # 第一拍时间
    count = -1  # 计数器
    bpm = -1  # bpm记录

    def __init__(self, timeout: int = 3):
        super().__init__()  # 调用父类构造方法，创建主窗口
        self.timeout = timeout  # 超时时间
        self.timer = threading.Timer(self.timeout, self.reset)  # 初始化计时器

        # 初始化，链接UI
        self.setupUi(self)  # 调用Ui_Form中的setupUi，需要传入参数Form，由于自身继承了Form所以传入自身
        self.pushButton_tap.pressed.connect(self.tap)
        self.pushButton_reset.pressed.connect(self.reset)

        # 获取必要数据
        self.window_title = self.windowTitle()  # 获取原始窗口名

    def tap(self):
        """
        计数一拍
        """
        self.timer.cancel()  # 取消计时器，停止重置计时

        self.count += 1
        if self.count == 0:
            self.time = time.time()
            self.lcd_bpm.display(0)
        else:
            minute = (time.time() - self.time) / 60
            self.bpm = round(self.count / minute, 2)
            self.lcd_bpm.display(self.bpm)  # 更新BPM计算
        self.lcd_count.display(self.count)  # 更新count

        self.timer = threading.Timer(self.timeout, self.reset)
        self.timer.start()

    def reset(self):
        """
        重置计数器
        """
        if self.count != -1:
            self.setWindowTitle(self.window_title + f"  BPM: {self.bpm}  Count: {self.count}")  # 置入有效数据
        self.time = None
        self.count = -1
        self.lcd_bpm.display(-1)
        self.lcd_count.display(-1)


if __name__ == '__main__':
    app = QApplication([])  # 创建应用类
    window = MyWindow()  # 创建窗口类
    window.show()  # 展示窗口
    app.exec()  # 启用管理
